//
//  HLEditPhotoWallCell.m
//  YueYue
//
//  Created by hulu001 on 2023/5/19.
//

#import "HLEditPhotoWallCell.h"
#import "HLPickerManager.h"
#import "HLImageStatusView.h"


@interface HLEditPhotoWallCell ()

@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) QMUIButton *tipButton;
@property (nonatomic, strong) UILabel *tipLabel;
@property (nonatomic, strong) QMUIFloatLayoutView *imagesView;
@property (nonatomic, strong) QMUIButton *uploadButton;
@property (nonatomic, strong) HLPickerManager *pickerManager;

@end

@implementation HLEditPhotoWallCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        self.contentView.backgroundColor = UIColorWhite;
        self.pickerManager = [[HLPickerManager alloc] initWithType:HXPhotoManagerSelectedTypePhoto avatar:NO];
        [self.pickerManager updateMaxNum:9 photos:nil];
        [self setupUI];
    }
    return self;
}

- (void)setupUI
{
    self.titleLabel = [[UILabel alloc] init];
    _titleLabel.font = UIFontMediumMake(13);
    _titleLabel.textColor = HLTextColor3;
    _titleLabel.text = @"照片墙";
    [self.contentView addSubview:_titleLabel];
    [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_equalTo(12);
    }];
    
    self.tipButton = [[QMUIButton alloc] init];
    [_tipButton setImage:UIImageMake(@"edit_cell_tip") forState:UIControlStateNormal];
    [_tipButton addTarget:self action:@selector(tipAction) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:_tipButton];
    [_tipButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_titleLabel);
        make.right.mas_equalTo(-12);
    }];
    
    self.tipLabel = [[QMUILabel alloc] init];
    _tipLabel.font = UIFontMake(16);
    _tipLabel.textColor = HLTextColor3;
    _tipLabel.text = @"";
    [self.contentView addSubview:_tipLabel];
    [_tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_tipButton);
        make.right.equalTo(_tipButton.mas_left).offset(-4);
    }];
    
    CGFloat width = (SCREEN_WIDTH - 48)/3;
    
    self.imagesView = [[QMUIFloatLayoutView alloc] init];
    _imagesView.padding = UIEdgeInsetsMake(4, 4, 4, 4);
    _imagesView.itemMargins = UIEdgeInsetsMake(4, 4, 4, 4);
    _imagesView.minimumItemSize = CGSizeMake(width, width);
    _imagesView.maximumItemSize = CGSizeMake(width, width);
    [self.contentView addSubview:_imagesView];
    [_imagesView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(12);
        make.right.mas_equalTo(-12);
        make.height.mas_equalTo(width + 8);
        make.bottom.mas_equalTo(-20);
        make.top.equalTo(_titleLabel.mas_bottom).offset(10);
    }];
    
    self.uploadButton = [[QMUIButton alloc] init];
    [_uploadButton setImage:UIImageMake(@"edit_cell_photo") forState:UIControlStateNormal];
    [_uploadButton addTarget:self action:@selector(uploadAction) forControlEvents:UIControlEventTouchUpInside];
    [_uploadButton.imageView setContentMode:UIViewContentModeScaleAspectFit];
    [self.imagesView addSubview:_uploadButton];

}

- (void)setModel:(HLUserInfoModel *)model
{
    _model = model;
    
    self.titleLabel.text = [NSString stringWithFormat:@"照片墙 (%ld/%@)", (model.userOpuses.count + model.userOpuseImages.count), HLUserPhotoWallCount];
    
    [self updateImages];
}

- (void)tipAction
{
    [_model tipAction];
}

- (void)updateImages
{
    [self.imagesView qmui_removeAllSubviews];
    
    NSInteger previewTag = HLCommonTagA + 1000;
    NSInteger urlCloseTag = HLCommonTagA;
    for (HLOpusModel *opus in [_model imagesWithUserOpuses]) {
        HLImageStatusView *wallImageView = [[HLImageStatusView alloc] init];
        [wallImageView.imageView sd_setImageWithURL:[NSURL URLWithString:opus.opusLink]];
        urlCloseTag = (urlCloseTag + 1);
        wallImageView.closeButton.tag = urlCloseTag;
        [wallImageView.closeButton addTarget:self action:@selector(deletePhotoUrl:) forControlEvents:UIControlEventTouchUpInside];
        previewTag = previewTag + 1;
        wallImageView.previewButton.tag = previewTag;
        [wallImageView.previewButton addTarget:self action:@selector(previewButton:) forControlEvents:UIControlEventTouchUpInside];
        [self.imagesView addSubview:wallImageView];
    }
    
    NSInteger imageCloseTag = HLCommonTagB;
    for (UIImage *image in _model.userOpuseImages) {
        HLImageStatusView *wallImageView = [[HLImageStatusView alloc] init];
        wallImageView.imageView.image = image;
        imageCloseTag = imageCloseTag + 1;
        wallImageView.closeButton.tag = imageCloseTag;
        [wallImageView.closeButton addTarget:self action:@selector(deletePhotoImage:) forControlEvents:UIControlEventTouchUpInside];
        previewTag = previewTag + 1;
        wallImageView.previewButton.tag = previewTag;
        [wallImageView.previewButton addTarget:self action:@selector(previewButton:) forControlEvents:UIControlEventTouchUpInside];
        [self.imagesView addSubview:wallImageView];
    }
    
    NSInteger editCount = [HLUserPhotoWallCount integerValue] - self.imagesView.subviews.count;
    [self.pickerManager updateMaxNum:editCount photos:nil];
    for (int i = 0; i < editCount; i++){
        QMUIButton *editButton = [[QMUIButton alloc] init];
        [editButton setImage:UIImageMake(@"edit_cell_photo") forState:UIControlStateNormal];
        [editButton addTarget:self action:@selector(uploadAction) forControlEvents:UIControlEventTouchUpInside];
        [editButton.imageView setContentMode:UIViewContentModeScaleAspectFit];
        [self.imagesView addSubview:editButton];
    }
    
    CGFloat width = (SCREEN_WIDTH - 56)/3;
    if ([self.imagesView.subviews count] > 6){
        
        [self.imagesView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(width * 3 + 16);
        }];
    } else if ([self.imagesView.subviews count] > 3){
        
        [self.imagesView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(width * 2 + 12);
        }];
    } else {
        [self.imagesView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(width + 8);
        }];
    }
}

- (void)previewButton:(UIButton *)button
{
    NSInteger index = button.tag - HLCommonTagA - 1001;
    [self evokeHXPicker:index];
}

- (void)deletePhotoUrl:(QMUIButton *)button
{
    NSInteger index = button.tag - HLCommonTagA - 1;
    HLOpusModel *opus = [[_model imagesWithUserOpuses] objectAtIndex:index];
    NSMutableArray *mImages = [NSMutableArray arrayWithArray:_model.userOpuses];
    [mImages removeObject:opus];
    _model.userOpuses = [mImages copy];
    _model.userOpuseUrlsChangeState = @"1";
    [self reloadData];
}

- (void)deletePhotoImage:(QMUIButton *)button
{
    NSInteger index = button.tag - HLCommonTagB - 1;
    NSMutableArray *mImages = [NSMutableArray arrayWithArray:_model.userOpuseImages];
    [mImages removeObjectAtIndex:index];
    _model.userOpuseImages = [mImages copy];
    [self reloadData];
}

- (void)reloadData
{
    [self.qmui_tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:2]] withRowAnimation:UITableViewRowAnimationNone];
}

- (void)uploadAction
{
    MJWeakSelf;
    [self.pickerManager showWithController:self.qmui_viewController block:^(NSArray<HXPhotoModel *> *photos) {
        NSMutableArray *ps = [NSMutableArray array];
        for (HXPhotoModel *photo in photos) {
            [photo getImageWithSuccess:^(UIImage * _Nullable image, HXPhotoModel * _Nullable model, NSDictionary * _Nullable info) {
                [ps addObject:image];
                
                if (ps.count == photos.count){
                    if (weakSelf.model.userOpuseImages.count > 0){
                        [ps addObjectsFromArray:weakSelf.model.userOpuseImages];
                    }
                    [weakSelf.model setUserOpuseImages:[ps copy]];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        weakSelf.model.userOpuseUrlsChangeState = @"1";
                        [weakSelf reloadData];
                    });
                }
            } failed:nil];
        }
    }];
}

- (void)evokeHXPicker:(NSInteger)index
{
    HXPhotoManager *photoManager = [HXPhotoManager managerWithType:HXPhotoManagerSelectedTypePhotoAndVideo];

    
    NSMutableArray *models = [NSMutableArray array];
    for (HLOpusModel *opus in _model.userOpuses) {
        HXCustomAssetModel *model = [HXCustomAssetModel assetWithNetworkImageURL:[NSURL URLWithString:opus.opusLink] selected:YES];
        [models addObject:model];
    }
    
    for (UIImage *image in _model.userOpuseImages) {
        HXCustomAssetModel *model = [HXCustomAssetModel assetWithLocalImage:image selected:YES];
        [models addObject:model];
    }
    
    [photoManager addCustomAssetModel:models];
    [HLPickerManager previewWithManager:photoManager index:index controller:self.qmui_viewController];
    
    

}

@end
